<template>
  <view class="market-trend-container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="title">市场趋势分析</view>
      <view class="subtitle">{{analysisStore.timeRangeText}}图书销售趋势变化</view>
    </view>
    
    <!-- 操作栏 -->
    <view class="action-bar">
      <view class="time-granularity">
        <view 
          v-for="(item, index) in timeGranularities" 
          :key="index" 
          :class="['granularity-item', analysisStore.filter.granularity === item.value ? 'active' : '']"
          @click="switchGranularity(item.value)"
        >
          <text>{{item.label}}</text>
        </view>
      </view>
    </view>
    
    <!-- 趋势总览卡片 -->
    <view class="overview-card">
      <view class="overview-item">
        <text class="item-value">{{trendData.totalSales || '0'}}</text>
        <text class="item-label">总销量</text>
      </view>
      <view class="overview-item">
        <text class="item-value">{{trendData.averageSales || '0'}}</text>
        <text class="item-label">平均销量</text>
      </view>
      <view class="overview-item">
        <text class="item-value">{{trendData.growth || '0%'}}</text>
        <text class="item-label">环比增长</text>
      </view>
    </view>
    
    <!-- 图表区域 -->
    <view class="chart-area" v-if="!isLoading">
      <!-- 使用图表组件显示趋势数据 -->
      <qiun-data-charts 
        type="line" 
        :chart-data="chartDataObject" 
        :loading="chartLoading"
        canvas-id="trend-chart"
        canvas-height="350px"
      ></qiun-data-charts>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-container" v-if="isLoading">
      <uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
    </view>
    
    <!-- 趋势数据表格 -->
    <view class="trend-table" v-else>
      <view class="section-title">销售趋势明细</view>
      
      <scroll-view scroll-y class="trend-scroll">
        <view class="table-header">
          <view class="table-cell time-cell">时间段</view>
          <view class="table-cell sales-cell">销量</view>
          <view class="table-cell growth-cell">增长率</view>
        </view>
        
        <view 
          class="table-row" 
          v-for="(item, index) in trendData.details" 
          :key="index"
        >
          <view class="table-cell time-cell">{{item.period}}</view>
          <view class="table-cell sales-cell">{{item.sales}}</view>
          <view class="table-cell growth-cell" :class="{'positive': item.growth > 0, 'negative': item.growth < 0}">
            {{item.growth > 0 ? '+' : ''}}{{item.growth}}%
          </view>
        </view>
        
        <!-- 无数据提示 -->
        <view class="no-data" v-if="!trendData.details || trendData.details.length === 0">
          <text>暂无趋势数据</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部操作区 -->
    <view class="footer-actions">
      <button class="action-btn export-btn" @click="exportData">
        <text class="iconfont icon-download"></text>
        <text>导出数据</text>
      </button>
      <button class="action-btn refresh-btn" @click="refreshData">
        <text class="iconfont icon-refresh"></text>
        <text>刷新</text>
      </button>
    </view>
  </view>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useAnalysisStore } from '@/store/analysis.js';
import QiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue';

export default {
  name: 'MarketTrend',
  components: {
    QiunDataCharts
  },
  setup() {
    // 获取分析数据仓库
    const analysisStore = useAnalysisStore();
    
    // 时间粒度选项
    const timeGranularities = [
      { label: '日', value: 'day' },
      { label: '周', value: 'week' },
      { label: '月', value: 'month' },
      { label: '季度', value: 'quarter' },
      { label: '年', value: 'year' }
    ];
    
    // 趋势数据
    const trendData = reactive({
      totalSales: 0,
      averageSales: 0,
      growth: '0%',
      details: []
    });
    
    // 页面加载状态
    const isLoading = ref(true);
    // 图表加载状态
    const chartLoading = ref(false);
    // 加载文字
    const loadingText = {
      contentdown: '上拉显示更多',
      contentrefresh: '数据加载中...',
      contentnomore: '没有更多数据了'
    };
    
    // 图表数据对象
    const chartDataObject = computed(() => {
      // 如果没有趋势数据，返回空数据结构
      if (!trendData.details || trendData.details.length === 0) {
        return {
          categories: [],
          series: []
        };
      }
      
      // 准备图表数据
      const result = {};
      
      // 设置分类（时间段）
      result.categories = trendData.details.map(item => item.period);
      
      // 构建系列数据
      result.series = [
        {
          name: '销量',
          data: trendData.details.map(item => item.sales)
        }
      ];
      
      return result;
    });
    
    // 页面初始化
    onMounted(() => {
      loadMarketTrendData();
    });
    
    // 监听时间粒度变化
    watch(
      () => analysisStore.filter.granularity,
      (newVal) => {
        loadMarketTrendData();
      }
    );
    
    // 加载市场趋势数据
    async function loadMarketTrendData() {
      isLoading.value = true;
      chartLoading.value = true;
      try {
        // 获取市场趋势数据
        const data = await analysisStore.fetchMarketTrend(analysisStore.filter.granularity);
        
        // 更新趋势总览数据
        if (data) {
          trendData.totalSales = data.totalSales || 0;
          trendData.averageSales = data.averageSales || 0;
          trendData.growth = (data.growth || 0) + '%';
          trendData.details = data.details || [];
        }
      } catch (error) {
        console.error('加载市场趋势数据失败:', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      } finally {
        isLoading.value = false;
        chartLoading.value = false;
      }
    }
    
    // 切换时间粒度
    function switchGranularity(granularity) {
      analysisStore.setFilter({ granularity });
      // 粒度变化会触发watch，自动重新加载数据
    }
    
    // 刷新数据
    function refreshData() {
      loadMarketTrendData();
    }
    
    // 导出数据
    function exportData() {
      const csvContent = analysisStore.exportToCSV('trend');
      
      // 在真实环境中，这里会处理CSV导出
      // 由于小程序和H5环境的限制，这里只做简单提示
      uni.showModal({
        title: '导出成功',
        content: '在实际环境中，这里会下载销售趋势数据的CSV文件',
        showCancel: false
      });
      
      console.log('导出的CSV数据：', csvContent);
    }
    
    return {
      analysisStore,
      timeGranularities,
      loadingText,
      trendData,
      isLoading,
      chartLoading,
      chartDataObject,
      switchGranularity,
      refreshData,
      exportData
    };
  }
};
</script>

<style lang="scss">
.market-trend-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
  
  /* 顶部标题样式 */
  .header {
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }
    
    .subtitle {
      font-size: 24rpx;
      color: #999999;
      margin-top: 10rpx;
    }
  }
  
  /* 操作栏样式 */
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .time-granularity {
      display: flex;
      
      .granularity-item {
        padding: 10rpx 20rpx;
        margin-right: 10rpx;
        font-size: 26rpx;
        color: #666666;
        border-radius: 30rpx;
        background-color: #f5f5f5;
        
        &.active {
          background-color: #0066ff;
          color: #ffffff;
        }
      }
    }
  }
  
  /* 趋势总览卡片样式 */
  .overview-card {
    display: flex;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .overview-item {
      flex: 1;
      text-align: center;
      padding: 0 20rpx;
      position: relative;
      
      &:not(:last-child):after {
        content: '';
        position: absolute;
        right: 0;
        top: 20%;
        height: 60%;
        width: 1px;
        background-color: #f0f0f0;
      }
      
      .item-value {
        font-size: 40rpx;
        color: #0066ff;
        font-weight: bold;
        display: block;
        /* 如果值太长需要截断 */
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .item-label {
        font-size: 24rpx;
        color: #999999;
        margin-top: 10rpx;
        display: block;
      }
    }
  }
  
  /* 图表区域样式 */
  .chart-area {
    background-color: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 30rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
  
  /* 加载状态样式 */
  .loading-container {
    padding: 40rpx 0;
  }
  
  /* 趋势数据表格样式 */
  .trend-table {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .section-title {
      font-size: 30rpx;
      font-weight: 500;
      color: #333333;
      margin-bottom: 20rpx;
    }
    
    .trend-scroll {
      max-height: 500rpx;
    }
    
    .table-header {
      display: flex;
      padding: 20rpx 0;
      font-weight: bold;
      color: #333333;
      border-bottom: 2px solid #f0f0f0;
    }
    
    .table-row {
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
    }
    
    .table-cell {
      font-size: 26rpx;
      
      &.time-cell {
        flex: 2;
      }
      
      &.sales-cell {
        flex: 1;
        text-align: center;
      }
      
      &.growth-cell {
        flex: 1;
        text-align: right;
        
        &.positive {
          color: #00cc66;
        }
        
        &.negative {
          color: #ff6666;
        }
      }
    }
    
    .no-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      color: #999999;
      font-size: 26rpx;
    }
  }
  
  /* 底部操作区样式 */
  .footer-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
    
    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48%;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      
      .iconfont {
        margin-right: 10rpx;
      }
      
      &.export-btn {
        background-color: #ffffff;
        color: #0066ff;
        border: 1px solid #0066ff;
      }
      
      &.refresh-btn {
        background-color: #0066ff;
        color: #ffffff;
      }
    }
  }
}
</style>
